package cn.imnu.legalaid.controller;

import cn.imnu.legalaid.dto.Appointment.AppointmentCreateDTO;
import cn.imnu.legalaid.dto.Appointment.AppointmentDTO;
import cn.imnu.legalaid.dto.Appointment.AppointmentQueryDTO;
import cn.imnu.legalaid.dto.Appointment.AppointmentUpdateDTO;
import cn.imnu.legalaid.service.AppointmentsService;
import cn.imnu.legalaid.util.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/appointment")
public class AppointmentController {

    @Autowired
    private AppointmentsService appointmentsService;

    /**
     * 创建预约
     */
    @PostMapping
    public Result<Map<String, Object>> createAppointment(@RequestBody AppointmentCreateDTO createDTO) {
        try {
            Integer appointmentId = appointmentsService.createAppointment(createDTO);
            Map<String, Object> data = new HashMap<>();
            data.put("id", appointmentId);
            return Result.success(data, "预约创建成功");
        } catch (Exception e) {
            log.error("创建预约失败", e);
            return Result.error("创建预约失败: " + e.getMessage());
        }
    }

    /**
     * 获取预约列表（分页+筛选）
     */
    @GetMapping
    public Result<Map<String, Object>> getAppointments(AppointmentQueryDTO queryDTO) {
        try {
            Page<AppointmentDTO> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());
            Page<AppointmentDTO> result = appointmentsService.getAppointments(page, queryDTO);

            Map<String, Object> data = new HashMap<>();
            data.put("records", result.getRecords());
            data.put("total", result.getTotal());
            data.put("current", result.getCurrent());
            data.put("size", result.getSize());

            return Result.success(data, "获取预约列表成功");
        } catch (Exception e) {
            log.error("获取预约列表失败", e);
            return Result.error("获取预约列表失败");
        }
    }

    /**
     * 获取预约详情
     */
    @GetMapping("/{id}")
    public Result<AppointmentDTO> getAppointmentDetail(@PathVariable Integer id) {
        try {
            AppointmentDTO appointment = appointmentsService.getAppointmentDetail(id);
            if (appointment == null) {
                return Result.error("预约不存在");
            }
            return Result.success(appointment, "获取预约详情成功");
        } catch (Exception e) {
            log.error("获取预约详情失败", e);
            return Result.error("获取预约详情失败");
        }
    }

    /**
     * 更新预约信息
     */
    @PutMapping("/{id}")
    public Result<AppointmentDTO> updateAppointment(@PathVariable Integer id,
                                                    @RequestBody AppointmentUpdateDTO updateDTO) {
        try {
            AppointmentDTO appointment = appointmentsService.updateAppointment(id, updateDTO);
            return Result.success(appointment, "预约更新成功");
        } catch (Exception e) {
            log.error("更新预约失败", e);
            return Result.error("更新预约失败: " + e.getMessage());
        }
    }

    /**
     * 取消预约
     */
    @PutMapping("/{id}/cancel")
    public Result<Void> cancelAppointment(@PathVariable Integer id) {
        try {
            appointmentsService.cancelAppointment(id);
            return Result.success(null, "预约取消成功");
        } catch (Exception e) {
            log.error("取消预约失败", e);
            return Result.error("取消预约失败: " + e.getMessage());
        }
    }

    /**
     * 确认预约
     */
    @PutMapping("/{id}/confirm")
    public Result<Void> confirmAppointment(@PathVariable Integer id) {
        try {
            appointmentsService.confirmAppointment(id);
            return Result.success(null, "预约确认成功");
        } catch (Exception e) {
            log.error("确认预约失败", e);
            return Result.error("确认预约失败: " + e.getMessage());
        }
    }

    /**
     * 完成预约
     */
    @PutMapping("/{id}/complete")
    public Result<Void> completeAppointment(@PathVariable Integer id) {
        try {
            appointmentsService.completeAppointment(id);
            return Result.success(null, "预约完成");
        } catch (Exception e) {
            log.error("完成预约失败", e);
            return Result.error("完成预约失败: " + e.getMessage());
        }
    }

    /**
     * 更新预约状态
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateAppointmentStatus(@PathVariable Integer id,
                                                @RequestBody Map<String, String> request) {
        try {
            String status = request.get("status");
            appointmentsService.updateAppointmentStatus(id, status);
            return Result.success(null, "预约状态更新成功");
        } catch (Exception e) {
            log.error("更新预约状态失败", e);
            return Result.error("更新预约状态失败");
        }
    }

    /**
     * 检查时间冲突
     */
    @PostMapping("/check-conflict")
    public Result<Map<String, Object>> checkTimeConflict(@RequestBody Map<String, Object> request) {
        try {
            Integer lawyerId = (Integer) request.get("lawyerId");
            String scheduledTimeStr = (String) request.get("scheduledTime");
            Integer duration = (Integer) request.get("duration");
            Integer excludeId = (Integer) request.get("excludeId");

            java.time.LocalDateTime scheduledTime = java.time.LocalDateTime.parse(scheduledTimeStr);

            boolean hasConflict = appointmentsService.checkTimeConflict(lawyerId, scheduledTime, duration, excludeId);

            Map<String, Object> data = new HashMap<>();
            data.put("hasConflict", hasConflict);

            return Result.success(data, "时间冲突检查完成");
        } catch (Exception e) {
            log.error("检查时间冲突失败", e);
            return Result.error("检查时间冲突失败");
        }
    }
}